package com.barbeque.mall.service.wx;

import com.barbeque.mall.bean.advertise.MarketCoupon;
import com.barbeque.mall.bean.advertise.MarketCouponExample;
import com.barbeque.mall.bean.advertise.MarketCouponUser;
import com.barbeque.mall.bean.advertise.MarketCouponUserExample;
import com.barbeque.mall.bean.config.MarketSystem;
import com.barbeque.mall.bean.goods.MarketGoods;
import com.barbeque.mall.bean.goods.MarketGoodsProduct;
import com.barbeque.mall.bean.user.MarketAddress;
import com.barbeque.mall.bean.user.MarketAddressExample;
import com.barbeque.mall.bean.wx.cart.*;
import com.barbeque.mall.mapper.*;
import com.barbeque.mall.util.OrderConstant;
import com.barbeque.mall.util.UserInfoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author ycc
 * @date 2022/07/18 20:15:20
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    MarketCartMapper cartMapper;

    @Autowired
    MarketGoodsMapper goodsMapper;

    @Autowired
    MarketGoodsProductMapper goodsProductMapper;

    @Autowired
    MarketAddressMapper addressMapper;

    @Autowired
    MarketCouponMapper couponMapper;

    @Autowired
    MarketCouponUserMapper couponUserMapper;

    @Autowired
    MarketGrouponRulesMapper grouponRulesMapper;

    @Autowired
    MarketOrderMapper orderMapper;

    @Autowired
    MarketSystemMapper systemMapper;

    //显示购物车的所有订单
    @Override
    public IndexOfCartVo index() {
        //1.获取购物车所有商品信息cartList
        List<MarketCart> cartList = cartMapper.selectByExample(getCartExample(null));
        //购物车所有商品总金额
        BigDecimal goodsAmount = getTotalPrice(cartList);
        //点击选中的商品
        List<MarketCart> checkedCartList = cartMapper.selectByExample(getCartExample(OrderConstant.CHECKED));
        //确认付款的金额
        BigDecimal checkedGoodsAmount = getTotalPrice(checkedCartList);

        //2.获取cartTotal
        CartTotalOfIndexOfCartVo cartTotal = new CartTotalOfIndexOfCartVo();
        //购物车订单总数量
        cartTotal.setGoodsCount(cartList.size());
        //确认的订单总数量
        cartTotal.setCheckedGoodsCount(checkedCartList.size());
        //订单总金额
        cartTotal.setGoodsAmount(goodsAmount);
        //确认的订单总金额
        cartTotal.setCheckedGoodsAmount(checkedGoodsAmount);

        IndexOfCartVo indexOfCartVo = new IndexOfCartVo();
        indexOfCartVo.setCartList(cartList);
        indexOfCartVo.setCartTotal(cartTotal);
        return indexOfCartVo;
    }

    //获取购物车商品总价
    private BigDecimal getTotalPrice(List<MarketCart> cartList) {
        BigDecimal goodsAmount = new BigDecimal(0.0);
        for (MarketCart cart : cartList) {
            BigDecimal cartPrice = cart.getPrice();
            BigDecimal number = new BigDecimal(cart.getNumber());
            goodsAmount = goodsAmount.add(cartPrice.multiply(number));
        }
        return goodsAmount;
    }
    //获取购物车商品
    private MarketCartExample getCartExample(Boolean checked) {
        //获取用户信息
        int userId = UserInfoUtils.getUserId();
        MarketCartExample cartExample = new MarketCartExample();
        //拼接select语句
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        //根据用户id选择
        criteria.andUserIdEqualTo(userId);
        //删除的订单不显示
        criteria.andDeletedEqualTo(false);
        //点击选择商品
        if (checked!=null) {
            criteria.andCheckedEqualTo(checked);
        }else {
            criteria.andCheckedIsNotNull();
        }
        return cartExample;
    }

    //点击选中
    @Override
    public IndexOfCartVo checked(CheckedOfCartBo checkedBo) {
        int userId = UserInfoUtils.getUserId();
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andProductIdIn(checkedBo.getProductIds());
        criteria.andDeletedEqualTo(false);

        MarketCart marketCart = new MarketCart();
        if (checkedBo.getIsChecked()==OrderConstant.CHECKED_CODE) {
            marketCart.setChecked(false);
        }else {
            marketCart.setChecked(true);
        }

        int update = cartMapper.updateByExampleSelective(marketCart,cartExample);

        if (update==0) {
            throw new RuntimeException("暂时无法选中");
        }

        return index();
    }

    //修改订单中商品的数量
    @Override
    public int update(MarketCart cart) {
        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(cart.getId());
        return cartMapper.updateByExampleSelective(cart, example);
    }

    //删除订单
    @Override
    public IndexOfCartVo delete(Map map) {
        int userId = UserInfoUtils.getUserId();
        List<Integer> productIds = new LinkedList<>();
        if (map.containsKey("productIds")) {
            productIds = (List<Integer>) map.get("productIds");
        }
        MarketCart marketCart = new MarketCart();
        marketCart.setDeleted(true);
        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andProductIdIn(productIds);
        int update = cartMapper.updateByExampleSelective(marketCart, example);
        if (update==0) {
            throw new RuntimeException("暂时无法删除");
        }
        return index();
    }

    //加入购物车
    @Override
    public long add(MarketCart cart) {
        Integer userId = UserInfoUtils.getUserId();
        //TODO:加入购物车时，先查找购物车中是否有同样的商品，如果有，只加数量
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andGoodsIdEqualTo(cart.getGoodsId());
        criteria.andProductIdEqualTo(cart.getProductId());
        criteria.andDeletedEqualTo(false);
        criteria.andCheckedIsNotNull();
        List<MarketCart> marketCarts = cartMapper.selectByExample(cartExample);
        if (marketCarts.size()>0) {
            MarketCart marketCart = marketCarts.get(0);
            marketCart.setNumber((short) (marketCart.getNumber()+cart.getNumber()));
            int update = cartMapper.updateByExampleSelective(marketCart, cartExample);
            if (update!=0) {
                return cartMapper.countByExample(getCartExample(null));
            }else {
                return OrderConstant.FAILED_CODE;
            }
        }
        //获取加入购物车的商品参数
        getMarketCart(cart);
        //加入购物车
        int selective = cartMapper.insertSelective(cart);
        //添加失败，返回结果状态码
        if (selective ==0) {
            return OrderConstant.FAILED_CODE;
        }
        //返回购物车商品的总数
        return cartMapper.countByExample(getCartExample(null));
    }

    private void getMarketCart(MarketCart cart) {
        int userId = UserInfoUtils.getUserId();
        Integer goodsId = cart.getGoodsId();
        Integer productId = cart.getProductId();
        MarketGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
        MarketGoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(productId);

        cart.setUserId(userId);
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setGoodsName(goods.getName());
        cart.setPrice(goodsProduct.getPrice());
        cart.setSpecifications(goodsProduct.getSpecifications());
        cart.setChecked(false);
        cart.setPicUrl(goodsProduct.getUrl());
        cart.setDeleted(false);
        cart.setAddTime(new Date());
    }

    //下单
    @Override
    public CheckoutOfCartVo checkout(CheckoutOfCartBo cartBo) {
        Integer cartId = cartBo.getCartId();
        Integer couponId = cartBo.getCouponId();
        Integer userCouponId = cartBo.getUserCouponId();
        Integer addressId = cartBo.getAddressId();
        Integer grouponRulesId = cartBo.getGrouponRulesId();

        Integer userId = UserInfoUtils.getUserId();
        //1.商品信息
        List<MarketCart> checkedGoodsList;
        if (cartId!=0) {
            MarketCart marketCart = cartMapper.selectByPrimaryKey(cartId);
            checkedGoodsList = new LinkedList<>();
            checkedGoodsList.add(marketCart);
        }else {
            //如果cartId为0——>通过购物车点选下单
            checkedGoodsList = cartMapper.selectByExample(getCartExample(true));
        }
        //商品总金额
        BigDecimal goodsTotalPrice = new BigDecimal(0.0);

        //2.运费
        MarketSystem freightMinSystem = systemMapper.selectByPrimaryKey(OrderConstant.EXPRESS_FREIGHT_MIN_ID);
        MarketSystem freightValueSystem = systemMapper.selectByPrimaryKey(OrderConstant.EXPRESS_FREIGHT_VALUE_ID);
        String freightMinStr = freightMinSystem.getKeyValue();
        String freightValueStr = freightValueSystem.getKeyValue();
        BigDecimal freightMin = new BigDecimal(freightMinStr);
        BigDecimal freightValue = new BigDecimal(freightValueStr);
        BigDecimal freightPrice = new BigDecimal(0.0);
        for (MarketCart marketCart : checkedGoodsList) {
            BigDecimal price = marketCart.getPrice();
            BigDecimal num = new BigDecimal(marketCart.getNumber());
            goodsTotalPrice = goodsTotalPrice.add(price.multiply(num));
            if (marketCart.getPrice().compareTo(freightMin)<0) {
                freightPrice = freightPrice.add(freightValue);
            }
        }
        //订单总计+运费
        BigDecimal actualPrice = goodsTotalPrice.add(freightPrice);

        //3.优惠券
        List<CouponUser> couponUsers = couponMapper.selectCouponByCondition(userId);
        BigDecimal couponPrice = new BigDecimal(0.0);
        //使用优惠券的最低金额
        BigDecimal min;
        /*if (userCouponId<=0) {
            //没有指定优惠券默认使用第一个
            if (couponUsers.size()>0) {
                CouponUser coupon = couponUsers.get(0);
                userCouponId = coupon.getCouponUserId();
                couponId = coupon.getCouponId();
                couponPrice = coupon.getDiscount();
            }
        }else {
            MarketCouponUser couponUser = couponUserMapper.selectByPrimaryKey(userCouponId);
            if (couponUser!=null) {
                Integer couponUserCouponId = couponUser.getCouponId();
                MarketCoupon marketCoupon = couponMapper.selectByPrimaryKey(couponUserCouponId);
                //优惠券满减价格
                min = marketCoupon.getMin();
                //如果商品总价高于优惠券满减价格
                if (goodsTotalPrice.compareTo(min)>=0) {
                    couponPrice = marketCoupon.getDiscount();
                }
            }
        }*/
        if (userCouponId!=-1) {
            MarketCouponUser couponUser = couponUserMapper.selectByPrimaryKey(userCouponId);
            if (couponUser!=null) {
                Integer couponUserCouponId = couponUser.getCouponId();
                MarketCoupon marketCoupon = couponMapper.selectByPrimaryKey(couponUserCouponId);
                //优惠券满减价格
                min = marketCoupon.getMin();
                //如果商品总价高于优惠券满减价格
                if (goodsTotalPrice.compareTo(min)>=0) {
                    couponPrice = marketCoupon.getDiscount();
                }
            }
        }
        //订单总计+运费-优惠价
        actualPrice = actualPrice.subtract(couponPrice);

        //4.地址
        MarketAddress address = null;
        if (addressId>0) {
            address = addressMapper.selectByPrimaryKey(addressId);
        }else {
            MarketAddressExample addressExample = new MarketAddressExample();
            addressExample.createCriteria()
                    .andDeletedEqualTo(false)
                    .andUserIdEqualTo(userId)
                    .andIsDefaultEqualTo(true);
            List<MarketAddress> marketAddresses = addressMapper.selectByExample(addressExample);
            if (marketAddresses.size()>0) {
                address = marketAddresses.get(0);
                addressId = address.getId();
            }
        }

        CheckoutOfCartVo checkout = new CheckoutOfCartVo();
        checkout.setActualPrice(actualPrice);
        checkout.setOrderTotalPrice(actualPrice);
        checkout.setCartId(cartId);
        checkout.setUserCouponId(userCouponId);
        checkout.setCouponId(couponId);
        checkout.setGoodsTotalPrice(goodsTotalPrice);
        checkout.setAddressId(addressId);
        checkout.setCheckedAddress(address);
        checkout.setCouponPrice(couponPrice);
        checkout.setCheckedGoodsList(checkedGoodsList);
        checkout.setAvailableCouponLength(couponUsers.size());
        checkout.setFreightPrice(freightPrice);
        return checkout;
    }

    //立即购买
    @Override
    public int fastadd(MarketCart cart) {
        int userId = UserInfoUtils.getUserId();
        //获取商品信息
        MarketGoods goods = goodsMapper.selectByPrimaryKey(cart.getGoodsId());
        MarketGoodsProduct product = goodsProductMapper.selectByPrimaryKey(cart.getProductId());
        //查找条件
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andGoodsIdEqualTo(cart.getGoodsId());
        criteria.andProductIdEqualTo(cart.getProductId());
        criteria.andNumberEqualTo(cart.getNumber());
        criteria.andPriceEqualTo(product.getPrice());
        criteria.andSpecificationsEqualTo(Arrays.toString(product.getSpecifications()));
        criteria.andCheckedIsNull();
        criteria.andPicUrlEqualTo(product.getUrl());
        List<MarketCart> marketCarts = cartMapper.selectByExample(cartExample);
        //TODO:先查找该商品是否存在,存在则返回该商品的cartId
        if (marketCarts.size()>0) {
            return marketCarts.get(0).getId();
        }

        //TODO:如果不存在，加入购物车，但是不显示在购物车
        cart.setUserId(userId);
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setGoodsName(goods.getName());
        cart.setPrice(goods.getRetailPrice());
        cart.setSpecifications(product.getSpecifications());
        cart.setChecked(null);
        cart.setPicUrl(product.getUrl());
        cart.setDeleted(true);
        //添加进购物车但不在购物车中显示
        cartMapper.insertSelective(cart);

        return cart.getId();
    }

    //获取购物车商品件数
    @Override
    public long goodscount() {
        return cartMapper.countByExample(getCartExample(null));
    }
}
